﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using SlamCmsDemo.Data;

namespace SlamCmsDemo.Web.Core
{
	public class CalendarResult : FileResult
	{
		public CalendarResult(Event @event) : base("text/calendar")
		{
			Event = @event;
			base.FileDownloadName = "CalendarEvent.ics";
		}

		public Event Event { get; set; }

		protected override void WriteFile(HttpResponseBase response)
		{
			response.Write("BEGIN:VCALENDAR\r\n");
			response.Write("PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN");
			response.Write("VERSION:2.0");
			response.Write("METHOD:PUBLISH");
			response.Write("X-MS-OLK-FORCEINSPECTOROPEN:TRUE");
			response.Write("BEGIN:VEVENT");
			response.Write("CLASS:PUBLIC");
			response.Write("CREATED:" + DateTime.Now.ToString("yyyyMMddT172948Z"));
			response.Write("DESCRIPTION:" + Regex.Replace(Event.Description, @"<(.|\n)*?>", string.Empty));
			response.Write("DTSTAMP:" + DateTime.Now.ToString("yyyyMMdd"));
			response.Write("DTSTART:" + Event.StartDate.ToString("yyyyMMddTHHmmssZ")); 
			response.Write("DTEND:" + Event.EndDate.ToString("yyyyMMddTHHmmssZ")); 
			response.Write("PRIORITY:5");
			response.Write("SEQUENCE:0");
			response.Write("SUMMARY:" + Event.Title);

			if (Event.Location != null)
				response.Write("LOCATION:" + Event.Location);

			response.Write("TRANSP:OPAQUE");
			response.Write("UID:1");
			response.Write("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
			response.Write("X-MICROSOFT-CDO-IMPORTANCE:1");
			response.Write("END:VEVENT");
			response.Write("END:VCALENDAR");
		}
	}
}